package ext.tianma.part;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.ptc.windchill.enterprise.part.commands.PartDocServiceCommand;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;
import ext.generic.part.CusIBAUtil;
import ext.tianma.bom.eco.BOMHelp;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.part.forms.TransitFactoryUtil;
import wt.doc.WTDocument;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.part.LineNumber;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartDescribeLink;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.config.ConfigException;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.vc.struct.StructHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;
import wt.vc.wip.WorkInProgressHelper;

/**
 * 天马BOM审核流程 发送C08 BOM 至中间表
 * @author Administrator
 *
 */
public class SubmitBomReview {
	private static final String D_VIEW = "Design";
	private static final String View_C08 = "C08";
	/** Log4j Logger. */
	private static final Logger LOGGER = LogR.getLogger(SubmitBomReview.class.getName());

	private static final String CLASSNAME = TransitFactoryUtil.class.getName();

	private static final String NEW_PRODUCT = "NewProduct";

	private static final String MASS_PRODUCTION_RELEASE = "MassProductionRelease";

	private static final String INWORK = "INWORK";

	private static final String APPROVAL = "APPROVAL";
	// 物料生效地
	private static final String PART_NUMBER_EFFECTIVE_SITE = "partNumberEffectiveSite";
	// 物料发布状态
	private static final String PART_RELESE_STATUS = "partReleaseStatus";
	// BOM发布状态
	private static final String BOM_RELEASE_STATUS = "bomReleaseStatus";

	// 成品的模组产地
	private static final String MODULEORIGIN = "moduleOrigin";
	private static List<String> rawMaterialStateList = new ArrayList<String>();

	static {
		rawMaterialStateList.add(APPROVAL);
		rawMaterialStateList.add(MASS_PRODUCTION_RELEASE);
		rawMaterialStateList.add(NEW_PRODUCT);
		rawMaterialStateList.add(INWORK);
	}
	/**
	 * 取C08视图物料
	 * 如果存在则更新C08 BOM结构
	 * 若不存在则转厂
	 * @param parts
	 * @return
	 */
	public static WTArrayList SendBOM( WTArrayList parts){
		String[] factorys = {"C08"};
		List<WTPart> checkInPartList = new ArrayList<WTPart>();
		WTArrayList newparts = new WTArrayList();
		try {
			if( parts == null ){

				System.out.println(">>>>> Error : erpObjs == null !");
			}else{
				//添加C08物料
				for( int i=0 ; i<parts.size() ; i++ ){
					Persistable persistable = parts.getPersistable(i) ;
					if( persistable != null && persistable instanceof WTPart ){
						WTPart part = ( WTPart ) persistable ;
						if (part != null) {
							part.getViewName();
							newparts.add(part);
							//C08视图
							WTPart aPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) part.getMaster(), View_C08);
							System.out.println("====C08 aPart 00:"+aPart+"==view:"+aPart.getViewName());
							aPart = BOMHelp.getPart(part.getNumber(),"",View_C08);
							System.out.println("====C08 aPart:"+aPart);
							if(aPart!=null && !parts.contains(aPart)){
								System.out.println("====C08 aPart 1:"+aPart);
								//重置C08视图BOM结构
								//1.先删除原有link
								/*aPart = (WTPart) CoreUtil.checkoutObject(aPart);
								if (!checkInPartList.contains(aPart)) {
									checkInPartList.add(aPart);
								}
								List<WTPartUsageLink> usageList = getAllUsageLink(aPart);
								for(WTPartUsageLink link : usageList){
									WTPart parent = link.getUsedBy();
									parent = (WTPart) CoreUtil.checkoutObject(parent);
									System.out.println("======start delete========");
									PersistenceHelper.manager.delete(link);
									System.out.println("======start end========");
									if (!checkInPartList.contains(parent)) {
										checkInPartList.add(parent);
									}
								}
								LOGGER.debug("Debug   usageList:" + usageList);*/
								//2.新建link
								tansitPartAndChildrenFactory(part, factorys);
								//aPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) part.getMaster(), View_C08);
								aPart = BOMHelp.getPart(part.getNumber(),"",View_C08);
								if(aPart!=null){
									newparts.add(aPart);
								}
							}else if(aPart == null){
								//方法一： 转厂
								tansitPartAndChildrenFactory(part, factorys);
								//aPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) part.getMaster(), View_C08);
								aPart = BOMHelp.getPart(part.getNumber(),"",View_C08);

								if(aPart!=null && !parts.contains(aPart)){
									System.out.println("====C08 aPart 2:"+aPart);
									newparts.add(aPart);
								}
							}
						}
						
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace()	;
			
		}finally {
			try {
				checkInAllPart(checkInPartList);
			} catch (WTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return newparts;
	}
	/**
	 * 获取指定零部件的所有usageLink
	 * 
	 * @param part
	 * @return
	 */
	private static List<WTPartUsageLink> getAllUsageLink(WTPart part) {
		List<WTPartUsageLink> usageLinkList = new ArrayList<WTPartUsageLink>();

		if (part != null) {

			usageLinkList = MyPartUtil.getAllUsageLink(part);

		}

		return usageLinkList;
	}
	/**
	 * 获取零部件的所有子件
	 * 
	 * @param part
	 * @param allSubPartList
	 * @return
	 * @throws WTException
	 */
	private static List<WTPart> getAllSubPart(WTPart part, List<WTPart> allSubPartList) throws WTException {
		if (allSubPartList == null) {
			allSubPartList = new ArrayList<WTPart>();
		}

		ConfigSpec latestconfigspec = getConfigSpec(part);

		QueryResult qr = StructHelper.service.navigateUsesToIteration(part, WTPartUsageLink.class, false,
				latestconfigspec);

		while (qr != null && qr.hasMoreElements()) {
			// 每一个element实际是一个persistable数组
			Persistable apersistable[] = (Persistable[]) qr.nextElement();

			Object uses = apersistable[1];

			WTPart subPart = null;
			if (uses instanceof WTPart) {
				subPart = (WTPart) uses;
			} else if (uses instanceof WTPartMaster) {
				WTPartMaster master = (WTPartMaster) uses;

				// 获取最新版本
				subPart = CoreUtil.getWTPartByMasterAndView(master, part.getViewName());
			} else {

			}

			if (subPart != null) {
				// 如果列表中不包含此零部件，则加入列表，并进行递归
				if (!allSubPartList.contains(subPart)) {
					allSubPartList.add(subPart);

					getAllSubPart(subPart, allSubPartList);
				}
			}
		}

		return allSubPartList;
	}

	/**
	 * 
	 * @param part
	 * @return
	 */
	private static ConfigSpec getConfigSpec(WTPart part) {
		ConfigSpec latestconfigspec = new LatestConfigSpec();

		String view = "";
		ViewReference viewRef = part.getView();
		if (viewRef != null) {
			view = viewRef.getName();
		}
		try {
			if (view != null && view.length() > 0) {
				View viewObj = ViewHelper.service.getView(view);
				WTPartConfigSpec config = WTPartHelper.service.findWTPartConfigSpec();
				WTPartStandardConfigSpec standardConfig = config.getStandard();

				standardConfig.setView(viewObj);
				latestconfigspec = standardConfig;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return latestconfigspec;
	}
	
	/**
	 * 检查零部件状态是否符合要求(新品和量产发布)2013-11
	 * 
	 * @param allPartList
	 * 
	 * @return
	 */
	private static void checkAllSubPartState(List<WTPart> allPartList, StringBuffer stbPartLog) {
		if (allPartList != null && allPartList.size() > 0) {
			Iterator<WTPart> iterator = allPartList.iterator();

			while (iterator.hasNext()) {
				WTPart part = iterator.next();

				if (part != null) {

					// 二级物料不做转厂不需要检查状态
					if (!TMTypeUtil.isTwoLevelMaterial(part) && !TMTypeUtil.isBLU(part)
							&& !TMTypeUtil.isFPC_PCB(part)) {
						State partState = part.getLifeCycleState();

						if (partState != null) {
							String state = partState.toString();

							if ((!rawMaterialStateList.contains(state))) {
								stbPartLog.append(part.getNumber());
								stbPartLog.append("\n");
							}
						}
					}
				}
			}
		}
	}
	/**
	 * 重构新视图下的结构
	 * 
	 * @param part
	 * @param usageList
	 * @param factorys
	 * @throws WTException
	 */
	private static void createPartUsageLink(WTPart part, List<WTPartUsageLink> usageList, String[] factorys,
			List<WTPart> checkInPartList) throws WTException {
		if (!isDesignPart(part)) {

			if (factorys != null) {

				for (int i = 0; i < factorys.length; i++) {
					String viewName = factorys[i];

					if (viewName != null) {
						createPartUsageLink(usageList, viewName, checkInPartList);
					}
				}
			}
		}
	}

	/**
	 * 重新构建usageLink关系
	 * 
	 * @param part
	 * @param usageList
	 */
	private static void createPartUsageLink(List<WTPartUsageLink> usageList, String viewName,
			List<WTPart> checkInPartList) {

		if (usageList == null) {
			return;
		}

		try {
			Iterator<WTPartUsageLink> iterator = usageList.iterator();
			while (iterator.hasNext()) {
				WTPartUsageLink wtPartUsageLink = iterator.next();

				if (wtPartUsageLink != null) {
					WTPart parent = wtPartUsageLink.getUsedBy();
					WTPart newParent = CoreUtil.getWTPartByMasterAndView((WTPartMaster) parent.getMaster(), viewName);

					if (newParent != null) {

						if (partUsageLinkiIsExisted(wtPartUsageLink, newParent)) {
							LOGGER.debug("Debug   partUsageLinkiIsExisted:"
									+ partUsageLinkiIsExisted(wtPartUsageLink, newParent));
							continue;
						} else {
							// 重新设置usageLink的父件需要检出零部件
							LOGGER.debug("Debug   newParent:" + newParent.getViewName());
							newParent = (WTPart) CoreUtil.checkoutObject(newParent);
							wtPartUsageLink.setUsedBy(newParent);
							PersistenceHelper.manager.save(wtPartUsageLink);
							LOGGER.debug("Debug   checkoutnewParent:" + WorkInProgressHelper.isCheckedOut(newParent));

							if (!checkInPartList.contains(newParent)) {
								checkInPartList.add(newParent);
							}
						}
					}
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		} finally {

		}
	}
	/**
	 * 零部件批量转厂，包括List列表中的所有零部件
	 * 
	 * @param partList
	 * @param factorys
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static void tansitFactory(List<WTPart> partList, String[] factorys) throws RemoteException, WTException {
		if (partList == null) {
			return;
		}

		Iterator<WTPart> partListIte = partList.iterator();
		WTPart aPart = null;
		while (partListIte.hasNext()) {
			aPart = partListIte.next();

			tansitFactory(aPart, factorys);
		}
	}

	/**
	 * 零部件转厂
	 * 
	 * @param part
	 *            需要转厂的零部件
	 * @param factorys
	 *            需要生效的物料生效地
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static void tansitFactory(WTPart part, String[] factorys) throws RemoteException, WTException {
		if (part == null) {
			return;
		}

		// 获取设计视图最新版本
		WTPart dPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) part.getMaster(), D_VIEW);

		if (dPart == null) {
			throw new WTException("零部件" + part.getDisplayIdentifier() + "没有" + D_VIEW + "视图的版本");
		}

		if (factorys == null) {
			return;
		}

		List<String> newFactoryList = new ArrayList<String>();

		try {
			if (!TMTypeUtil.isTwoLevelMaterial(dPart) && !TMTypeUtil.isBLU(dPart) && !TMTypeUtil.isFPC_PCB(dPart)) {
				// 不是二级物料的时候需要做转厂以及拷贝IBA属性
				for (int i = 0; i < factorys.length; i++) {
					if (factorys[i] != null) {
						factorys[i] = factorys[i].trim();
						System.out.println("===factorys[i]:"+factorys[i]);

						if (!factorys[i].equals("")) {
							// 执行转视图操作
							WTPart newViewPart = tansitView(dPart, factorys[i], newFactoryList,
									part.getLifeCycleState());

							if (newViewPart != null) {
								// 部分IBA属性不做拷贝，例如：物料生效地
								copyIBAValues(dPart, newViewPart);

							}
						}
					}
				}
			} else {
				// 是二级物料的时候只需要跟新物料生效地
				for (int i = 0; i < factorys.length; i++) {
					if (factorys[i] != null) {
						factorys[i] = factorys[i].trim();

						if (!factorys[i].equals("")) {
							newFactoryList.add(factorys[i]);
						}
					}
				}
			}

		} finally {
			// 获取设计视图零部件当前的物料生效地
			String dPartEffectiveSite = "";
			Vector vector = IBAUtil.getIBAValue2(dPart, PART_NUMBER_EFFECTIVE_SITE);
			// add kwang 2013-12-09
			if (vector != null) {

				for (int i = 0; i < vector.size(); i++) {
					Object strObject = vector.get(i);

					if (strObject != null) {

						if (dPartEffectiveSite.equals("")) {
							dPartEffectiveSite = (String) strObject;
						} else {
							dPartEffectiveSite = dPartEffectiveSite + "," + (String) strObject;
						}
					}
				}
			}

			LOGGER.debug("Debug   finally...dPartEffectiveSite:" + dPartEffectiveSite);
			setDesignEffectiveSite(dPart, dPartEffectiveSite, newFactoryList);
		}
	}

	/**
	 * 对零部件执行转视图操作
	 * 
	 * @param dPart
	 *            设计视图零部件
	 * @param newFactory
	 *            新视图
	 * @param newFactoryList
	 *            收集新视图的列表
	 * 
	 * @return WTPart 转视图后生成的零部件新视图版本
	 */
	private static WTPart tansitView(WTPart dPart, String newFactory, List<String> newFactoryList, State state) {
		WTPart newViewPart = null;

		System.out.println("dPart======>>>"+dPart.getNumber()+"===>>视图==》》"+dPart.getViewName());
		// dPart必须是Design视图的零部件，才能执行转视图
		if (canTansitView(dPart)) {
			boolean flag = SessionServerHelper.manager.setAccessEnforced(false);

			try {
				WTPart aPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) dPart.getMaster(), newFactory);
				System.out.println("newFactory======>>>"+newFactory);
				// 如果可以获取newFactory视图的零部件，则说明此产地的零部件已经存在，不必再重新转视图
				if (aPart != null) {
					String aPartView = aPart.getViewName();
					System.out.println("视图==》》"+dPart.getViewName());
					if ((!aPartView.equals(D_VIEW)) && aPartView.equals(newFactory)) {
						
						newFactoryList.add(newFactory);

						newViewPart = aPart;
						return newViewPart;
					}
				}

				// 根据Design视图的零部件，生成新的视图版本 begin
				newViewPart = (WTPart) ViewHelper.service.newBranchForView(dPart, newFactory);
				System.out.println("newViewPart===>>"+newViewPart.getViewName());
				// xuge 设置物料的创建者和修改者
				/*
				 * WTPrincipal curUser= SessionHelper.manager.getPrincipal();
				 * WTPrincipalReference dpartPrincipalReference = dPart.getCreator();
				 * LOGGER.debug("dpartPrincipalReference" + dpartPrincipalReference.getName());
				 * 
				 * LOGGER.debug("SessionHelper.manager.getPrincipal" + curUser.getName());
				 * WTPrincipalReference wtprincipalreference =
				 * WTPrincipalReference.newWTPrincipalReference(curUser);
				 * VersionControlHelper.assignIterationCreator(newViewPart,
				 * dpartPrincipalReference);
				 */
				newViewPart = (WTPart) PersistenceHelper.manager.save(newViewPart);
				// VersionControlHelper.setIterationModifier(newViewPart,
				// dpartPrincipalReference);
				/**
				 * end
				 */
				// 新建视图版本成功，将此版本对应的物料生效地添加到List中，以便更新Design视图零部件的物料生效地
				newFactoryList.add(newFactory);

				// 设置生命周期状态为“正在工作”
				newViewPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(newViewPart, State.INWORK);

				// 原材料转厂之后，转完厂的零部件的状态为转厂前的的状态
				if (TMTypeUtil.isRawMaterial(newViewPart)) {

					newViewPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(newViewPart, state);

				}
				// 更新新视图零部件的物料生效地
				IBAUtil.forceSetIBAValue(newViewPart, PART_NUMBER_EFFECTIVE_SITE, newFactory);
				/**
				 * @author xuge_ning 成品模组产地枚举值的处理 begin
				 */
				if (TMTypeUtil.isFinishedGood(dPart)) {

					Vector modelOrigin = IBAUtil.getIBAValue2(dPart, MODULEORIGIN);
					LOGGER.debug(CLASSNAME + "模组产地：modelOrigin:" + modelOrigin.toString());
					String model = "";
					if (modelOrigin != null) {
						for (int i = 0; i < modelOrigin.size(); i++) {
							Object obj = modelOrigin.get(i);
							if (obj != null && obj instanceof String) {
								if (model.equals("")) {
									model = (String) obj;
								} else {
									model = model + "," + (String) obj;
								}
							}
						}
						LOGGER.debug(CLASSNAME + "模组产地：model：" + model);
						CusIBAUtil.forceSetEnumIBAValue(newViewPart, MODULEORIGIN, model);
					}
				}
				/**
				 * end
				 */

			} catch (WTException e) {
				e.printStackTrace();
			} catch (WTPropertyVetoException e) {
				e.printStackTrace();
			} catch (RemoteException e) {
				e.printStackTrace();
			} finally {
				SessionServerHelper.manager.setAccessEnforced(flag);
			}
		}

		return newViewPart;
	}

	/**
	 * 判断零部件是否可以执行转视图操作
	 * 
	 * @param dPart
	 * @return
	 */
	private static boolean canTansitView(WTPart dPart) {
		boolean result = true;

		// 零部件不能为null
		if (dPart == null) {
			LOGGER.debug("Warning Info : 用于转厂的目标零部件为NULL对象");

			result = false;
		} else {
			String dPartViewName = dPart.getViewName();

			// 零部件视图必须是Design视图
			if (!D_VIEW.equals(dPartViewName)) {
				LOGGER.debug("Warning Info : 用于转厂的目标零部件为：" + dPart.getDisplayIdentifier());
				LOGGER.debug("Warning Info : 用于转厂的目标零部件不是设计视图的版本，不能执行转厂操作。");

				result = false;
			}
		}

		return result;
	}

	public static void copyIBAValues(WTPart part, WTPart newViewPart) {
		try {
			Hashtable values = IBAUtil.getIBAValues(part);
			copyIBAValues(values, newViewPart);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 同编号不同视图的两个零部件对IBA属性做拷贝
	 * 
	 * @param part
	 * @param newViewPart
	 */
	public static void copyIBAValues(Hashtable values, WTPart newViewPart) {
		try {

			// 物料生效地,物料发布状态和BOM发布状态属性不做拷贝
			if (values.containsKey(PART_NUMBER_EFFECTIVE_SITE)) {
				LOGGER.debug("Info : copyIBAValues method , Hashtable contains " + PART_NUMBER_EFFECTIVE_SITE
						+ ", Remove it from the Hashtable.");
				values.remove(PART_NUMBER_EFFECTIVE_SITE);
			}

			if (values.containsKey(PART_RELESE_STATUS)) {
				LOGGER.debug("Info : copyIBAValues method , Hashtable contains " + PART_RELESE_STATUS
						+ ", Remove it from the Hashtable.");
				values.remove(PART_RELESE_STATUS);
			}

			if (values.containsKey(BOM_RELEASE_STATUS)) {
				LOGGER.debug("Info : copyIBAValues method , Hashtable contains " + BOM_RELEASE_STATUS
						+ ", Remove it from the Hashtable.");
				values.remove(BOM_RELEASE_STATUS);
			}
			if (TMTypeUtil.isFinishedGood(newViewPart) && values.containsKey(MODULEORIGIN)) {
				LOGGER.debug("Info : copyIBAValues method , Hashtable contains " + MODULEORIGIN
						+ ", Remove it from the Hashtable.");
				values.remove(MODULEORIGIN);
			}
			IBAUtil.setSoftTypeIBAValues(newViewPart, values);
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更新设计视图零部件的物料生效地
	 * 
	 * @param part
	 * @param currentEffectiveSite
	 * @param factorys
	 * @throws WTException
	 * @throws RemoteException
	 */
	private static void setDesignEffectiveSite(WTPart dPart, String dPartEffectiveSite, List<String> newFactoryList)
			throws WTException, RemoteException {
		if (dPart == null) {
			return;
		}

		String viewName = dPart.getViewName();

		if (!D_VIEW.equals(viewName)) {
			dPart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) dPart.getMaster(), D_VIEW);

			if (dPart == null) {
				return;
			}
		}

		dPartEffectiveSite = getNewDPartEffectiveSite(dPartEffectiveSite, newFactoryList);

		LOGGER.debug("Debug   dPartEffectiveSite:" + dPartEffectiveSite);
		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			// 检出零部件
			dPart = (WTPart) CoreUtil.checkoutObject(dPart);

			// 更新物料生效地

			// 多值枚举设值
			// IBAUtil.forceSetIBAValue( part , PART_NUMBER_EFFECTIVE_SITE ,
			// currentEffectiveSite ) ;
			CusIBAUtil.forceSetEnumIBAValue(dPart, PART_NUMBER_EFFECTIVE_SITE, dPartEffectiveSite);

		} finally {
			if (WorkflowUtil.isObjectCheckedOut(dPart)) {
				// 检入零部件
				CoreUtil.checkinObject(dPart, "转厂完成");
			}
			SessionServerHelper.manager.setAccessEnforced(flag);
		}

	}

	/**
	 * 根据Design视图的Part本身的料号生效地IBA属性和新的料号生效地List列表，生成新的设计视图料号生效地属性值
	 * 
	 * @param dPartEffectiveSite
	 *            当前Design视图的零部件的料号生效地
	 * @param newFactoryList
	 *            新的料号生效地List列表
	 * 
	 * @return String 新的设计视图料号生效地IBA属性值
	 */
	private static String getNewDPartEffectiveSite(String dPartEffectiveSite, List<String> newFactoryList) {
		if (dPartEffectiveSite == null) {
			dPartEffectiveSite = "";
		}

		// 遍历newFactoryList，将物料生效地中没有的加到currentEffectiveSite中
		if (newFactoryList != null) {
			int size = newFactoryList.size();

			for (int i = 0; i < size; i++) {
				String newFactory = newFactoryList.get(i);

				if (newFactory != null) {
					newFactory = newFactory.trim();

					if (!newFactory.equals("")) {
						if (dPartEffectiveSite.equals("")) {
							dPartEffectiveSite = newFactory;
						} else {
							if (!dPartEffectiveSite.contains(newFactory)) {
								dPartEffectiveSite = dPartEffectiveSite + "," + newFactory;
							}
						}
					}
				}
			}
		}

		return dPartEffectiveSite;
	}
	/**
	 * 判断零部件视图是否为“Design”
	 * 
	 * @param part
	 * @return
	 */
	private static boolean isDesignPart(WTPart part) {
		boolean isDesignPart = false;

		if (part == null) {
			return isDesignPart;
		}

		String view = part.getViewName();

		if (D_VIEW.equals(view)) {
			isDesignPart = true;
		}
		return isDesignPart;
	}
	/**
	 * 通过LineNumber,子件Master判断两个对象是否相同
	 * 
	 * @param wtPartUsageLink
	 * @param newPartUsageLink
	 * @return
	 */
	private static boolean partUsageLinkiIsExisted(WTPartUsageLink wtPartUsageLink, WTPartUsageLink newPartUsageLink) {
		boolean partUsageLinkiIsExisted = false;

		if (wtPartUsageLink == null || newPartUsageLink == null) {
			return partUsageLinkiIsExisted;
		}
		// 位号
		String wtPartLinkNumber = getLinkNumber(wtPartUsageLink);
		String newPartLinkNumber = getLinkNumber(newPartUsageLink);
		// 子件Master
		WTPartMaster wtPartMaster = wtPartUsageLink.getUses();
		WTPartMaster newPartMaster = newPartUsageLink.getUses();

		if (wtPartLinkNumber.equals(newPartLinkNumber)) {

			if (PersistenceHelper.isEquivalent(wtPartMaster, newPartMaster)) {

				partUsageLinkiIsExisted = true;
			}
		}

		return partUsageLinkiIsExisted;
	}
	/**
	 * 判断指定WTPartUsageLink是否存在
	 * 
	 * @param wtPartUsageLink
	 * @return
	 * @throws WTException
	 * @throws ConfigException
	 */
	private static boolean partUsageLinkiIsExisted(WTPartUsageLink wtPartUsageLink, WTPart newParent)
			throws ConfigException, WTException {
		boolean partUsageLinkiIsExisted = false;

		if (wtPartUsageLink == null) {
			return partUsageLinkiIsExisted;
		}

		List<WTPartUsageLink> listLink = MyPartUtil.getAllLevelUsageLink(newParent);

		if (listLink != null) {

			LOGGER.debug("Debug   listLink:" + listLink.size());
			Iterator<WTPartUsageLink> iterator = listLink.iterator();

			while (iterator.hasNext()) {
				WTPartUsageLink newPartUsageLink = iterator.next();

				if (newPartUsageLink != null) {
					partUsageLinkiIsExisted = partUsageLinkiIsExisted(wtPartUsageLink, newPartUsageLink);
					LOGGER.debug("Debug   newPartUsageLink...partUsageLinkiIsExisted:" + partUsageLinkiIsExisted);
					if (partUsageLinkiIsExisted) {
						break;
					}
				}
			}
		}
		LOGGER.debug("Debug   partUsageLinkiIsExisted:" + partUsageLinkiIsExisted);
		return partUsageLinkiIsExisted;
	}
	/**
	 * 获取usageLink的number
	 * 
	 * @param usageLink
	 * @return
	 */
	private static String getLinkNumber(WTPartUsageLink usageLink) {
		String lineNumber = "";

		if (usageLink == null) {
			return lineNumber;
		}
		LineNumber pLineNumber = usageLink.getLineNumber();
		if (pLineNumber != null) {
			lineNumber = pLineNumber.getValue() + "";
		}

		return lineNumber;
	}
	/**
	 * 检入已检出的对象
	 * 
	 * @param checkInPartList
	 * @throws WTException
	 */
	private static void checkInAllPart(List<WTPart> checkInPartList) throws WTException {

		if (checkInPartList == null || checkInPartList.size() == 0) {
			return;
		}

		Iterator<WTPart> iterator = checkInPartList.iterator();
		while (iterator.hasNext()) {
			WTPart checkInPart = iterator.next();

			if (checkInPart != null) {
				CoreUtil.checkinObject(checkInPart, "转厂之后重新搭建结构");
			}
		}
	}
	/**
	 * 零部件转厂，包含零部件本身和他结构下的所有子件
	 * 
	 * @param part
	 * @param factorys
	 * @throws WTException
	 */
	public static void tansitPartAndChildrenFactory(WTPart part, String[] factorys) throws WTException {
		if (part == null) {
			return;
		}

		// 判断是否选择物料生效地
		if (factorys == null || factorys.length == 0) {
			throw new WTException("没有选择物料生效地请选择！");
		}

		List<WTPart> checkInPartList = new ArrayList<WTPart>();

		try {
			List<WTPart> allPartList = new ArrayList<WTPart>();

			// 将主料加入列表中
			allPartList.add(part);

			// 获取主料所有的子件，并加入列表
			allPartList = getAllSubPart(part, allPartList);
			List<WTPartUsageLink> usageList = getAllUsageLink(part);

			LOGGER.debug("Debug   usageList:" + usageList);
			// 检查所有子件的生命周期状态是否符合要求 2013-11-14
			StringBuffer stbPartLog = new StringBuffer();
			//checkAllSubPartState(allPartList, stbPartLog);
			//if (stbPartLog.length() > 0) {
			//	throw new WTException(stbPartLog + "状态不符合要求，无法进行转厂！");
			//}

			// 执行批量转厂操作
			tansitFactory(allPartList, factorys);
			// 重新构造新视图下的usageLink关系
			createPartUsageLink(part, usageList, factorys, checkInPartList);
			// 转厂完成后自动创建DescriptionLink
			createDescriptionLinkForTransitFactory(part);
			// 重新构造替代料与新的usageLink关系
		} catch (RemoteException e) {
			e.printStackTrace();
		} finally {
			checkInAllPart(checkInPartList);
		}
	}
	/**
	 * 转厂完成后自动创建DescriptionLink
	 * 
	 * @author he_zhang2
	 * @param targetObj
	 * @param eventType
	 * @return
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void createDescriptionLinkForTransitFactory(WTPart part) throws WTException, RemoteException {
		WTDocument doc = null;
		QueryResult qr = PartDocServiceCommand.getAssociatedDescribeDocuments(part);
		if (qr != null && qr.hasMoreElements()) {
			doc = (WTDocument) qr.nextElement();
			if (TMTypeUtil.isATypeObject(doc, ".ControlDocument")) {
				String item = ((String) IBAUtil.getIBAValue(doc, "Item")).trim();
				if (item != null) {
					// 获取物料的Design视图对象
					WTPart dpart = null;
					dpart = (WTPart) CoreUtil.getWTPartByNumberAndView(item, "Design");
					// 获取物料的其他所有视图对象
					WTArrayList partList = new WTArrayList();
					partList = PartWorkflowUtil.getAllPartViews(dpart);
					partList.add(dpart);
					// 创建DescriptionLink
					for (int i = 0; i < partList.size(); i++) {
						WTPart wtpart = null;
						wtpart = (WTPart) partList.getPersistable(i);
						WTPartDescribeLink link = WTPartDescribeLink.newWTPartDescribeLink(wtpart, doc);
						PersistenceServerHelper.manager.insert(link);
					}
				}
			}
		}
	}
}

